package cn.silver.module.configuration.service.impl;

import cn.silver.framework.core.config.SilverConfig;
import cn.silver.framework.core.constant.CacheNames;
import cn.silver.framework.core.exception.ServiceException;
import cn.silver.framework.core.utils.MapstructUtils;
import cn.silver.framework.mybatis.service.impl.DataServiceImpl;
import cn.silver.framework.redis.utils.RedisUtils;
import cn.silver.module.configuration.bean.ParamBean;
import cn.silver.module.configuration.domain.SysParam;
import cn.silver.module.configuration.mapper.SysParamMapper;
import cn.silver.module.configuration.param.ConfigParam;
import cn.silver.module.configuration.service.ISysParamService;
import cn.silver.module.system.service.ParamService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 参数配置 服务层实现
 *
 * @author Silver Zhou
 */
@Service
@RequiredArgsConstructor
public class SysParamServiceImpl extends DataServiceImpl<SysParamMapper, SysParam, ConfigParam, ParamBean> implements ISysParamService, ParamService {

    private final SilverConfig config;

    @Override
    public void init() {
        if (!config.isCacheLazy()) {
            this.loadCache();
        }
    }

    @Override
    public void loadCache() {
        List<ParamBean> beans = this.baseMapper.selectVoList();
        for (ParamBean bean : beans) {
            RedisUtils.setCacheObject(CacheNames.SYS_CONFIG, bean.getCode(), bean.getValue());
        }
    }

    /**
     * 根据键名查询参数配置信息
     *
     * @param configKey 参数key
     * @return 参数键值
     */
    @Override
//    @Cacheable(cacheNames = CacheNames.SYS_CONFIG, key = "#configKey")
    public String getConfigValue(String configKey) {
        String value = RedisUtils.getCacheObject(CacheNames.SYS_CONFIG, configKey);
        if (StringUtils.isNotBlank(value)) {
            SysParam retConfig = baseMapper.selectOne(new LambdaQueryWrapper<SysParam>()
                    .eq(SysParam::getCode, configKey));
            value = retConfig != null ? retConfig.getValue() : StringUtils.EMPTY;
            RedisUtils.setCacheObject(CacheNames.SYS_CONFIG, configKey, value);
        }
        return value;
    }

    /**
     * 新增参数配置
     *
     * @param model 参数配置信息
     * @return 结果
     */
//    @Override
//    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#model.code")
//    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
//    public boolean insert(ParamBean model) {
//        return super.insert(model);
//    }

    /**
     * 修改参数配置
     *
     * @param model 参数配置信息
     * @return 结果
     */
    @Override
//    @CachePut(cacheNames = CacheNames.SYS_CONFIG, key = "#model.code")
    public boolean update(ParamBean model) {
        int row = 0;
        SysParam config = MapstructUtils.convert(model, SysParam.class);
        if (config != null && StringUtils.isNotBlank(config.getId())) {
            SysParam temp = baseMapper.selectById(config.getId());
            if (!StringUtils.equals(temp.getCode(), config.getCode())) {
                RedisUtils.setCacheObject(CacheNames.SYS_CONFIG, config.getCode(), temp.getValue());
            }
            row = baseMapper.updateById(config);
        }
        return SqlHelper.retBool(row);
    }

    /**
     * 批量删除参数信息
     *
     * @param ids 需要删除的参数ID
     * @return
     */
    @Override
    public boolean deleteBatch(Collection<String> ids) {
        List<ParamBean> params = this.baseMapper.selectVoList(new LambdaQueryWrapper<SysParam>().eq(SysParam::getBuilt, Boolean.TRUE).in(SysParam::getId, ids));
        if (CollectionUtils.isNotEmpty(params)) {
            throw new ServiceException(String.format("内置参数【%1$s】不能删除 ", params.stream().map(ParamBean::getCode).collect(Collectors.joining(","))));
        }
        return SqlHelper.retBool(this.baseMapper.deleteByIds(ids));
    }

    /**
     * 重置参数缓存数据
     */
    @Override
    public void resetConfigCache() {
        RedisUtils.deleteKeys(CacheNames.SYS_CONFIG);
    }
}
